/*****************************
 * 可视化总览页面逻辑代码
 * 主要是三维场景浏览数据
 ****************************/
$(function () {
    function globe() {
        //场景视图，所有项目
        var _map, _viewer, _projects, _buildingLayer, _floorLayer, _stationLayer, _selectedBuilding;

        var _mapOption = {
            scene: {
                //默认视角参数
                center: { lat: 30.054604, lng: 108.885436, alt: 17036414, heading: 0, pitch: -90 },
                shadows: false, //是否启用日照阴影
                removeDblClick: true, //是否移除Cesium默认的双击事件

                //以下是Cesium.Viewer所支持的options【控件相关的写在另外的control属性中】
                sceneMode: 3, //3等价于Cesium.SceneMode.SCENE3D,

                //以下是Cesium.Scene对象相关参数
                showSun: true, //是否显示太阳
                showMoon: true, //是否显示月亮
                showSkyBox: true, //是否显示天空盒
                showSkyAtmosphere: true, //是否显示地球大气层外光圈
                fog: true, //是否启用雾化效果
                fxaa: true, //是否启用抗锯齿
                globe: {
                    depthTestAgainstTerrain: false, //是否启用深度监测
                    baseColor: '#546a53', //地球默认背景色
                    showGroundAtmosphere: true, //是否在地球上绘制的地面大气
                    enableLighting: false //是否显示昼夜区域
                },
                //以下是Cesium.ScreenSpaceCameraController对象相关参数
                cameraController: {
                    zoomFactor: 3.0, //鼠标滚轮放大的步长参数
                    minimumZoomDistance: 1, //地球放大的最小值（以米为单位）
                    maximumZoomDistance: 50000000, //地球缩小的最大值（以米为单位）
                    enableRotate: true, //2D和3D视图下，是否允许用户旋转相机
                    enableTranslate: true, //2D和哥伦布视图下，是否允许用户平移地图
                    enableTilt: true, // 3D和哥伦布视图下，是否允许用户倾斜相机
                    enableZoom: true, // 是否允许 用户放大和缩小视图
                    enableCollisionDetection: true //是否允许 地形相机的碰撞检测
                }
            },
            control: {
                homeButton: true, //视角复位按钮
                fullscreenButton: true, //全屏按钮
                compass: { bottom: '10px', right: '10px' },
            },
            basemaps: [
                {
                    name: '天地图卫星',
                    type: 'tdt',
                    layer: 'img_d',
                    key: ['304bc664f193742e0ad7ad3b77d5dccd'],
                    show: true
                },
                {
                    name: '天地图卫星',
                    type: 'tdt',
                    layer: 'img_z',
                    key: ['304bc664f193742e0ad7ad3b77d5dccd'],
                    show: true
                }
            ]
        };

        /************************
         * 初始化
         ************************/
        function init() {
            if (!_map) {
                //Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(80, 22, 130, 55);
                _map = new mars3d.Map('mars3dContainer', _mapOption);
                _viewer = _map.viewer;
                _buildingLayer = new mars3d.layer.GraphicLayer();
                _floorLayer = new mars3d.layer.GraphicLayer();
                _stationLayer = new mars3d.layer.GraphicLayer();
                _map.addLayer(_buildingLayer);
                _map.addLayer(_floorLayer);
                _map.addLayer(_stationLayer);
            }
            //TODO:可能会多次注册
            initEvent();
            loadProjects();
            //添加地图WMS服务，测试对比位置
            //loadWMS();
        }

        /************************
         * 初始化事件
         ************************/
        function initEvent() {
            $('#project_select').on('change', function () {
                _buildingLayer.clear(true);
                const project = _projects[$('#project_select').val()]
                var centerLat = (project.minLatitude + project.maxLatitude) / 2;
                var centerLng = (project.minLongitude + project.maxLongitude) / 2;
                var d = Math.max(project.maxLongitude - project.minLongitude, project.maxLatitude - project.minLatitude);
                var center = { lat: centerLat, lng: centerLng, alt: 250000 * d, heading: 0, pitch: -90 };
                _map.setSceneOptions({ center: center });
                _map.flyHome();
                showBuildings(project);
            })

            _map.on(mars3d.EventType.click, function (event) {
                if (!event.graphic) {
                    clearFloors();
                }
            });

            _buildingLayer.on(mars3d.EventType.click, function (event) {
                console.log('点击的对象2', event)
                if (event.graphic) {
                    const buildingId = event.graphic.id.replace('building_', '');
                    showFloors(buildingId);
                    event.graphic.setStyle({ opacity: 0.3 })
                }
            });
        }

        /************************
         * 加载所有项目数据
         ************************/
        function loadProjects() {
            $('#project_select').empty();
            $.post(`${Config.BASE_URL}/api/project/list-all`, JSON.stringify({}), function (response) {
                if (response.succeeded) {
                    _projects = response.data;
                    for (let index = 0; index < _projects.length; index++) {
                        const project = _projects[index];
                        $('#project_select').append(`<option value=${index}>${project.name}</option>`)
                    }
                    if (_projects.length > 0) {
                        const project = _projects[0];
                        var centerLat = (project.minLatitude + project.maxLatitude) / 2;
                        var centerLng = (project.minLongitude + project.maxLongitude) / 2;
                        var d = Math.max(project.maxLongitude - project.minLongitude, project.maxLatitude - project.minLatitude);
                        var center = { lat: centerLat, lng: centerLng, alt: 250000 * d, heading: 0, pitch: -90 };
                        _map.setSceneOptions({ center: center });
                        _map.flyHome();
                        showBuildings(project);
                    }
                }
            })
        }

        /**
         * 展示一个项目所有的建筑物
         * @param {*} project 
         */
        function showBuildings(project) {
            const buildings = project.buildings;
            buildings.forEach(building => {
                var entity = new mars3d.graphic.ModelEntity({
                    name: building.name,
                    id: 'building_' + building.id,
                    position: [building.x, building.y, building.height],
                    style: {
                        url: `${Config.BASE_URL}/api/building/download-model/${building.model}`
                    },
                })
                _buildingLayer.addGraphic(entity)
            });
        }

        /**
         * 展示一个建筑物的楼层
         * @param {*} buildingId 
         */
        function showFloors(buildingId) {
            $('#lg_floor').empty();
            $.get(`${Config.BASE_URL}/api/building/${buildingId}`, function (response) {
                if (response.succeeded) {
                    _selectedBuilding = response.data;
                    for (let index = 0; index < _selectedBuilding.floors.length; index++) {
                        const floor = _selectedBuilding.floors[index];
                        $('#lg_floor').append(`<a href="javascript: void(0);" class="list-group-item list-group-item-action">${floor.name}</a>`);
                    }
                    $('#lg_floor').fadeIn();
                    $('#lg_floor .list-group-item').on('click', function (e) {
                        _stationLayer.clear(true);
                        const index = $(e.target).index();
                        showFloor(index);
                    })
                    if (_selectedBuilding.floors.length > 0) {
                        showFloor(0)
                    }
                }
            })
        }

        /**
         * 展示单个图层
         * @param {*} index 
         */
        function showFloor(index) {
            _floorLayer.clear(true);
            $('#lg_floor .list-group-item').removeClass('active');
            $(`#lg_floor .list-group-item:nth-child(${index + 1})`).addClass('active')
            const floor = _selectedBuilding.floors[index];
            var entity = new mars3d.graphic.ModelEntity({
                name: floor.name,
                id: 'floor_' + floor.id,
                position: [floor.x, floor.y, floor.height],
                style: {
                    url: `${Config.BASE_URL}/api/floor/download-model/${floor.model}`,
                },
            })
            _floorLayer.addGraphic(entity)
            showStations(floor);
        }

        /**
         * 清除建筑物图层
         */
        function clearFloors() {
            $('#lg_floor').fadeOut();
            _floorLayer.clear(true);
            _buildingLayer.graphics.forEach(graphic => {
                graphic.setStyle({ opacity: 1 })
            });
            _stationLayer.clear(true);
        }

        /**
         * 展示一个楼层所有的基站
         * @param {*} floorId 
         */
        function showStations(floor) {
            $.get(`${Config.BASE_URL}/api/station/list-by-floor/${floor.id}`, function (response) {
                if (response.succeeded) {
                    response.data.forEach(station => {
                        if (station.position != null) {
                            var pointEntity = new mars3d.graphic.PointEntity({
                                name: station.iBeaconName,
                                id: 'station_point_' + station.id,
                                position: [station.position.x, station.position.y, floor.height + 1],
                                style: {
                                    color: "#ff0000",
                                    pixelSize: 4
                                }
                            });
                            const circleEntity = new mars3d.graphic.CircleEntity({
                                position: [station.position.x, station.position.y, floor.height + 1],
                                style: {
                                    radius: 8.0,
                                    material: mars3d.MaterialUtil.createMaterialProperty(mars3d.MaterialType.CircleWave, {
                                        color: "#ff0000",
                                        count: 1, // 单个圆圈
                                        speed: 5
                                    })
                                }
                            })
                            _stationLayer.addGraphic(pointEntity);
                            _stationLayer.addGraphic(circleEntity)
                        }
                    });
                }
            })
        }

        return {
            init: init,
            showFloors: showFloors
        }
    }

    window.Globe = globe();
})